<?php
include('../../../../common.php');
$cache_payment = cache::get('payment');
$config = $cache_payment['alipay']['payment_config'];

$info = $db->pe_select('pay', array('pay_id'=>pe_dbhold($_g_id)));
$post['app_id'] = $config['alipay_appid'];
$post['method'] = $_g_from = 'h5' ? 'alipay.trade.wap.pay' : 'alipay.trade.page.pay';
$post['format'] = 'JSON';
$post['return_url'] = "{$pe['host']}include/plugin/payment/alipay/return_url.php";
$post['charset'] = 'utf-8';
$post['sign_type'] = 'RSA2';
$post['timestamp'] = date('Y-m-d H:i:s');
$post['version'] = '1.0';
$post['biz_content']['notify_url'] = "{$pe['host']}include/plugin/payment/alipay/notify_url.php";
$post['biz_content']['subject'] = $info['order_name'];
$post['biz_content']['out_trade_no'] = $info['pay_id'];
$post['biz_content']['timeout_express'] = '48h';
$post['biz_content']['total_amount'] = $info['order_money'];
$post['biz_content']['quit_url'] = $pe['h5_host'];//手机版专属参数
$post['biz_content']['product_code'] = 'FAST_INSTANT_TRADE_PAY';
$post['sign'] = alipay_sign($post);

$html = "<form action='https://openapi.alipay.com/gateway.do?charset=utf-8' method='post' id='form'>";
foreach ($post as $k=>$v) {
	if (is_array($v)) $v = json_encode($v);
	$html .= "<input type='hidden' name='{$k}' value='{$v}'/>";
}
$html .= "<input type='submit' style='display:none;''></form><script>document.forms['form'].submit();</script>";
echo $html;

function alipay_sign($arr) {
	global $pe, $config;
	//签名步骤一：拼接成字符串
	ksort($arr);
	foreach ($arr as $k => $v) {
		if ($k != "sign" && $v != ""){
			is_array($v) && $v = json_encode($v);
			$sign .= "{$k}={$v}&";
		}
	}
	$sign = trim($sign, "&");
	//签名步骤二：RSA加密
    //$priKey = file_get_contents("{$pe['path']}include/plugin/payway/alipay_app/key/rsa_private_key1218.pem");
    
    //$config['alipay_my_private_key'] = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCmAmfqySE8qy1JVSOCWiG4wL+N/4wcVAN7xSryObipSWug38AKZO+AmHLvAhd5VR1PlocHX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RjGfVXBOJZxRPJ3c09JJucGawU2RMkdBqcaplrbSwcJQrXsLARNJc1xc65R5pp4kFrno47HPPthIQwKBgHo4iOYQwdeCN63TN2xLgX+u3Cp1wvw76iHziaBUlxz5S58CaKfjH+OeWbnfff+CWa8MO70nNQswQ4cC2bV7KNya0ZoKayhQYnzt+74kYVZ0ufE1ak0KukD83RiGWgbO4SWk7Ef5BSRWgaLhF/uRAEbDGrIIOKZq/tJFS2QPuwBxAoGAdnIL85IIA6j75U0eeMJCyZKwW1WcIXFykTuQHtcvXNVZU1FoJxp7DuPv0tJVRXFTtw6gnrIrQapMzxH7cjU/i32TS9nltbLzFeb3eRAPbOB0H8lPHv1xJjTbe+QaA966RwcLd/piGa4icBeLsPlP16PY8Hp/4Cu6HemO9G8Amqc=';
    $key = $config['alipay_my_private_key'];
    $key = "-----BEGIN RSA PRIVATE KEY-----\n".chunk_split($key, 64, "\n")."-----END RSA PRIVATE KEY-----\n";
    $res = openssl_get_privatekey($key);
    openssl_sign($sign, $sign_new, $res, OPENSSL_ALGO_SHA256);
    openssl_free_key($res);
	//base64编码
    $sign = base64_encode($sign_new);
    return $sign;
}